<?php
class Tourismorderrefund extends CS_Controller
{
    public function _init()
    {
        $this->load->helper(array('common'));
        $this->load->library('pagination');
        $this->load->model('tourism_order_refund_model', 'tourism_order_refund');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('cash_record_model', 'cash_record');
        $this->load->model('tourism_order_product_profit_model', 'tourism_order_product_profit');
        $this->load->model('express_record_model', 'express_record');
        $this->load->model('express_model', 'express');
        $this->load->model('operate_power_log_model', 'operate_power_log');
    }

    public function grid($pg = 1)
    {
        $page_num = 20;
        $num = ($pg - 1) * $page_num;
        $config['first_url'] = base_url('tourismorderrefund/grid') . $this->pageGetParam($this->input->get());
        $config['suffix'] = $this->pageGetParam($this->input->get());
        $config['base_url'] = base_url('tourismorderrefund/grid');
        $config['total_rows'] = $this->tourism_order_refund->total($this->input->get());
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_list'] = $this->pagination->create_links();
        $data['page_list'] = $this->tourism_order_refund->page_list($page_num, $num, $this->input->get());
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['refundStatus'] = array('1' => '申请退款', '2' => '同意退款', '3' => '否决退款');
        $data['refundFlag']   = array(1 => '未退款', 2 => '已退款');
        $data['url'] = $this->pageGetParam($this->input->get());
        $this->load->view('tourismorderrefund/grid', $data);
    }

    /*
     *退款操作详情
     * */
    public function info($id)
    {
        $result = $this->tourism_order_refund->getRefund($id);
        if ($result->num_rows() <= 0) {
            $this->error('tourismorderrefund/grid', '', '退款详情有误');
        }
        $refund = $result->row();

        $order = $this->tourism_order->findByOrderId($refund->order_id);
        $data['orderInfo'] = $order->row();
        $data['refund'] = $refund;
        $data['logistics'] = $this->express_record->findByNu($refund->logistics);
        $data['express'] = $this->express->findByName($refund->logistics_company);
        
        $data['refundStatus'] = array('1' => '申请退款', '2' => '同意退款', '3' => '否决退款');
        $data['refundFlag']   = array(1 => '未退款', 2 => '已退款');
        $this->load->view('tourismorderrefund/info', $data);
    }
    
    public function editPost()
    {
        $refund_id = $this->input->post('refund_id');
        $error = $this->validate();
        if (!empty($error)) {
            $this->error('tourismorderrefund/info', $refund_id, $error);
        }
        
        $this->db->trans_start();
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name.'-商品','record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode(array('refund_id'=>$refund_id,'goods_name'=>$this->input->post('goods_name'),'order_product_id'=>$this->input->post('order_product_id')))));
        $resultId = $this->tourism_order_refund->updateTourismOrderRefund($this->input->post());
        if ($this->input->post('status') == 3) { //拒绝退款需还原商品数量
            $this->tourism_order_product->setTourismNum($this->input->post());
        }
        $this->db->trans_complete();
    
        if ($resultId) {
            $this->success('tourismorderrefund/grid', '', '保存成功！');
        } else {
            $this->error('tourismorderrefund/edit', $refund_id, '保存失败！');
        }
    }
    
    public function validate()
    {
        $error = array();
        if ($this->validateParam($this->input->post('refund_content'))) {
            $error[] = '退货原因不能为空。';
        }
        if ($this->validateParam($this->input->post('status'))) {
            $error[] = '退款状态不能为空。';
        }
        return $error;
    }
    
    /**
     * 确认退款操作。
     * @param unknown $refundId
     * @param unknown $orderProductId
     * @param unknown $pg_now
     */
    public function confirm($refund_id, $pg_now=1)
    {
        $refund_res = $this->tourism_order_refund->findById($refund_id);
        if ($refund_res->num_rows() <= 0) {
            $this->error('tourismorderrefund/grid', $pg_now, '当前退款记录有误！');
        }
        $tourismRefund = $refund_res->row();
        
        $result = $this->tourism_order_product->getProductByProductId(array('order_id'=>$tourismRefund->order_id, 'order_product_id'=>$tourismRefund->order_product_id));
        if ($result->num_rows() <= 0) {
            $this->error('tourismorderrefund/grid', $pg_now, '当前订单产品有误！');
        }
        $orderProduct = $result->row(0);
        
        //获取订单信息
        $order_res = $this->tourism_order->findByOrderId($tourismRefund->order_id);
        if ($order_res->num_rows() <= 0) {
            $this->error('tourismorderrefund/grid', $pg_now, '当前订单有误！');
        }
        $orderInfo = $order_res->row();
        
        //订单是否退还运费 未发货时 并且无可退商品
        if (($orderInfo->order_state < 2) || ($orderInfo->order_status < 3)) {
            $this->error('tourismorderrefund/grid', $pg_now, '当前订单未付，不可退款！');
        }
        if (($orderInfo->order_state >= 4) || ($orderInfo->order_status >= 6)) {
            $this->error('tourismorderrefund/grid', $pg_now, '当前订单已评价或已退，不可退款！');
        }
        //验证退货数量是否大于0
        if ($tourismRefund->number <= 0) {
            $this->error('tourismorderrefund/grid', $pg_now, '退货数量必须大于0！');
        }
        //获取订单总商品数量 - 已退商品数量 - 获取本次退货数量 ==0 返还运费
        $number = $this->tourism_order_product->getAllProduct($tourismRefund->order_id);
        $refund_num = $this->tourism_order_refund->getAllRefundNum($tourismRefund->order_id);
        $num = $number - $refund_num - $tourismRefund->number;
        
        $this->db->trans_start();
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name.'-商品','record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($orderInfo)));
        $res_arr = $this->tourism_order_refund->updateOrderInfo($orderProduct, $tourismRefund, $tourismRefund->counter_fee, $num, $orderInfo);
        if (0 != $res_arr['err_code']) {
            $this->error('tourismorderrefund/grid', '', $res_arr['err_message']);
        }
        //获取用户账户信息
        $resultUser = $this->user_account->findByUid($tourismRefund->uid);
        if ($resultUser->num_rows() <= 0) {
            $this->error('tourismorderrefund/grid', $pg_now, '退款用户不存在。');
        }
        $userAccount = $resultUser->row(0);
        
        //分润
        $profit = $this->refundProductProfit($tourismRefund, $orderProduct->order_product_id);
        //退款到提现账户
        $account = $this->user_account->updateUserAcount($tourismRefund->uid, array('amount_carry' => $res_arr['actual_return']));
        
        //记录现金流
        $account_log = $this->account_log->insertAccountLogRecord($orderProduct->order_id, $tourismRefund->uid, $res_arr['amount_refund'], bcadd($userAccount->amount_carry,$res_arr['actual_return'],2), CANCEL, ACCOUNT_TYPE_CARRY, 'tourism');
        
        $totalAmountCarry =  bcadd($userAccount->amount_carry,$res_arr['actual_return'],2); //运费相加
        
        if ($res_arr['isTransport']) { //退运费
            //返还运费 生成记录
            $this->user_account->updateUserAcount($tourismRefund->uid, array('amount_carry' => $res_arr['transport_cost'], 'amount_bonus' => $res_arr['amount_bonus_return']));
            $account_log = $this->account_log->insertAccountLogRecord($orderProduct->order_id, $tourismRefund->uid, $res_arr['transport_cost'], bcadd($totalAmountCarry,$res_arr['transport_cost'],2), CANCEL, ACCOUNT_TYPE_CARRY, 'tourism');
        }
        
        $refundFlag = $this->tourism_order_refund->updateRefundFlag(array('flag'=>2, 'refund_id'=>$refund_id));
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === FALSE && !$profit || !$account_log || !$account || !$refundFlag) {
            $this->error('tourismorderrefund/grid', '', '确认退款操作失败');
        }
        $this->success('tourismorderrefund/grid', '', '确认退款操作成功');
    }
    
    //修改分润数据
    public function refundProductProfit($tourismRefund, $order_product_id)
    {
        $profitData = array();

        $profit = $this->tourism_order_product_profit->findById($order_product_id);
        //拼分润数据
        foreach ($profit->result_array() as $key => $value) {
            $profitData[$key] = $value;
            if ($tourismRefund->existing != 0) {
                $profitData[$key]['account'] = bcmul(bcdiv($value['account'], $tourismRefund->existing, 2), ($tourismRefund->existing - $tourismRefund->number), 2);
            }
        }
        $is_delete = $this->tourism_order_product_profit->delete($order_product_id);
        $is_add = $this->tourism_order_product_profit->addBatch($profitData);
        if (!$is_delete || !$is_add) {
            return false;
        }
        return true;
    }
}